<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerCategorySwippersManageModal"
    :title="displayModuleTitle"
    :default-fullscreen="false"
    :show-ok-btn="false"
    :body-style="{ height: '500px' }"
    width="1000px"
  >
    <BasicTable
      @register="registerCategorySwippersTable"
      :can-resize="true"
      :bordered="true"
      :striped="true"
      :loading="false"
      :data-source="swipperData.swippers"
    >
      <template #groupText="{ record }">
        <span v-if="record.groupid === 0">{{ '栏目轮播图组' }}</span>
        <span v-if="record.groupid === 1">{{ '横隔组1' }}</span>
        <span v-if="record.groupid === 2">{{ '横隔组2' }}</span>
        <span v-if="record.groupid === 3">{{ '横隔组3' }}</span>
        <span v-if="record.groupid === 4">{{ '横隔组4' }}</span>
        <span v-if="record.groupid === 5">{{ '横隔组5' }}</span>
        <span v-if="record.groupid === 6">{{ '横隔组6' }}</span>
        <span v-if="record.groupid === 7">{{ '横隔组7' }}</span>
        <span v-if="record.groupid === 8">{{ '横隔组8' }}</span>
        <span v-if="record.groupid === 9">{{ '横隔组9' }}</span>
      </template>

      <!-- 文章id显示 -->
      <template #articleidDisplay="{ record }">
        <span v-if="record.articleid === 0"> - </span>
        <span v-else>{{ record.articleid }}</span>
      </template>

      <!-- 图片id显示 -->
      <template #fidDisplay="{ record }">
        <span v-if="record.fid === 0"> - </span>
        <span v-else>{{ record.fid }}</span>
      </template>

      <!-- 是否跳转至栏目 -->
      <template #iscategoryFlag="{ record }">
        <template v-if="record.iscategory === true">
          <Tag :color="'cadetBlue'">是</Tag>
        </template>
        <template v-if="record.iscategory === false">
          <Tag :color="'DarkGray'">否</Tag>
        </template>
      </template>

      <template #statusFlag="{ record }">
        <Switch
          checkedChildren="启用"
          unCheckedChildren="禁用"
          :checked="record.flag === 0 ? true : false"
          :onChange="onChange"
          :onClick="switchOnClick.bind(null, record)"
        />
      </template>

      <template #toolbar>
        <a-button type="primary" @click="onAddSwipper"> 新增 </a-button>
      </template>

      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              label: '编辑',
              onClick: onEditSwipper.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              label: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: onDeleteSwipper.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <addOrUpdateSwipper @register="registerAddOrUpdateSwipperForm" @success="successReload" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, unref, computed } from 'vue';
  import { Switch } from 'ant-design-vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';

  import { swipperTableColumns } from './swipper.data';
  import { deleteSwipper, getCategorySwipperList } from '/@/api/cms/swipper';
  import { editFlag } from '/@/api/cms/swipper';
  import { SwipperQueryConditionDto } from '/@/api/cms/model/swipperModel';

  //引入子组件
  import addOrUpdateSwipper from './AddOrUpdateSwipper.vue';

  import { Tag } from 'ant-design-vue';

  const { createMessage } = useMessage();

  const [registerAddOrUpdateSwipperForm, { openModal: openAddOrUpdateForm }] = useModal();

  export default defineComponent({
    name: 'SetSwipperRelation',
    components: { BasicModal, BasicTable, TableAction, Switch, addOrUpdateSwipper, Tag },
    emits: ['success', 'register'],
    setup() {
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();

      //栏目id
      const categoryId = ref('');
      //栏目名称
      const categoryName = ref('');

      //返回的轮播图数据
      const swipperData = reactive({
        swippers: [],
      });

      const onChange = (checked: boolean) => {
        console.log(`switch to ${checked}`);
      };

      /**
       * 显示的模块标题，用于显示在弹出框中的标题
       */
      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      const [registerCategorySwippersTable] = useTable({
        title: '栏目轮播图',
        columns: swipperTableColumns, //表头数据
        showTableSetting: true, //是否显示表格设置
        bordered: true,
        showIndexColumn: false,
        actionColumn: {
          width: 80,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
        pagination: false, //关闭分页
      });

      /**
       * 接收父组件传递的数据并处理
       */
      const [registerCategorySwippersManageModal, { setModalProps }] = useModalInner(
        async (data: QcUnifyTransToChildProps) => {
          //接收父组件传递的数据
          console.log('registerCategorySwippersManageModal data', data);
          if (data != undefined && data != null) {
            qcUnifyProps.value = unref(data);
            //从父组件中传递过来的栏目ID
            categoryId.value = data.dataId;
            categoryName.value = data.dataTitle;
          }

          setModalProps({ confirmLoading: false });

          getSwipperList();
        },
      );

      /**
       * 获取指定栏目轮播图列表
       */
      async function getSwipperList() {
        //更新数据前先清空原来的数据，否则页面不刷新显示最新数据
        if (swipperData.swippers.length > 0) {
          swipperData.swippers = [];
        }
        //调用后端接口获取数据
        let params: SwipperQueryConditionDto = {
          cid: categoryId.value,
          count: 10,
        };
        getCategorySwipperList(params)
          .then((res) => {
            // console.log('getCategorySwipperList res', res);
            if (res != null) {
              //处理返回数据
              res.forEach((val) => {
                swipperData.swippers.push(val);
              });
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 启用/禁用轮播图
       */
      function switchOnClick(record: Recordable, checked: boolean) {
        // console.log(`onclick switch to`, checked);
        // console.log('record', record.id);
        editFlag({ id: record.id, flagStatus: checked })
          .then((res) => {
            createMessage.success('操作成功。', 2);
            successReload();
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 打开新增轮播图窗口
       */
      function onAddSwipper() {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: qcUnifyProps.value.moduleName,
          operateType: OperationTypeEnum.ADD,
          operateString: '新增轮播图',
          dataId: qcUnifyProps.value?.dataId,
          dataTitle: qcUnifyProps.value?.dataTitle,
        };

        //使用props传递数据至子组件，在data参数中指定
        openAddOrUpdateForm(true, propsData);
      }

      /**
       * 打开编辑轮播图窗口
       */
      function onEditSwipper(record: Recordable) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: qcUnifyProps.value.moduleName,
          operateType: OperationTypeEnum.EDIT,
          operateString: '修改轮播图',
          dataId: qcUnifyProps.value?.dataId,
          dataTitle: qcUnifyProps.value?.dataTitle,
          model: record,
        };

        openAddOrUpdateForm(true, propsData);
      }

      /**
       * 删除栏目轮播图信息
       */
      function onDeleteSwipper(record: Recordable) {
        deleteSwipper(record.id)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              successReload();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 确认操作之后刷新页面
       */
      function successReload() {
        getSwipperList();
      }

      return {
        displayModuleTitle,
        swipperData,
        registerCategorySwippersManageModal,
        registerCategorySwippersTable,
        registerAddOrUpdateSwipperForm,
        successReload,
        getSwipperList,
        onAddSwipper,
        onEditSwipper,
        onDeleteSwipper,
        onChange,
        switchOnClick,
      };
    },
  });
</script>
